import math
import datetime
from django.db import models
from django.contrib.auth.models import AbstractUser

# Create your models here.


class UserProfile(AbstractUser):
    """
    用户详情
    """
    GENDER_CHOICES = (
        ('female', '女'),
        ('male', '男'),
        ('secret', '保密')
    )
    nickname = models.CharField(verbose_name='昵称', max_length=20, null=True, blank=True, unique=True, help_text='昵称')
    avatar = models.ImageField(verbose_name='头像', upload_to='avatar/%Y/%m', default='avatar/default.png', max_length=200, help_text='头像')
    gender = models.CharField(verbose_name="性别", max_length=6, choices=GENDER_CHOICES, default='secret', help_text="性别")
    birthday = models.DateField(verbose_name="生日", null=True, blank=True, help_text="生日")
    mobile = models.CharField(verbose_name="手机号", max_length=11, null=True, blank=True, unique=True, help_text="手机号")
    address = models.CharField(verbose_name="地址", null=True, blank=True, max_length=200, help_text="地址")

    class Meta:
        verbose_name = "用户信息"
        verbose_name_plural = verbose_name

    def get_age(self):
        age = None
        if self.birthday:
            today = datetime.date.today()
            age = math.floor((today - self.birthday).days/365)
        return age
    get_age.short_description = "年龄"
    get_age.admin_order_field = 'birthday'

    def __repr__(self):
        return self.nickname or self.username

    __str__ = __repr__


class UserOperationLog(models.Model):
    user = models.ForeignKey(UserProfile, verbose_name="操作人", on_delete=models.CASCADE, help_text="操作人")
    operation = models.CharField(verbose_name="操作", max_length=100, help_text="记录用户进行的操作(函数)")
    resource = models.CharField(verbose_name='操作的资源', max_length=400, help_text='操作的资源')
    content = models.TextField(verbose_name="操作的内容", help_text="操作的内容")
    c_time = models.DateTimeField(verbose_name="创建时间", auto_now=True, editable=False, help_text="创建时间")
    m_time = models.DateTimeField(verbose_name="创建时间", auto_now=True, editable=False, help_text="创建时间")

    class Meta:
        db_table = 't_user_operation_log'
        verbose_name = "用户操作表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'{self.user.username}({self.operation} - {self.resource})'
